//暂时没有用到该结构
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var config=require('../config');
var Post=require('./post')
var Active=require('./avtive')
var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    console.log(error);
});
db.model('active',Active.activeSchema);
db.model('post',Post.postSchema);
var activeToPostSchema=new Schema({
    active:{type:Schema.Types.ObjectId,ref:'active'},
    post:{type:Schema.Types.ObjectId,ref:'post'},
    reply:Number
});
//users---对应数据库表名
var ActiveToPost=db.model('ActiveToPost',activeToPostSchema);
ActiveToPost.prototype.findActiveToPostByOption=function (options,callback){
    ActiveToPost.find(options).exec(function(err,datas){
        callback(err,datas);
    })

}
ActiveToPost.prototype.findDatasByActive=function (aid,callback){
    ActiveToPost.find({active:aid}).exec(function(err,datas){
        callback(err,datas);
    })
}
ActiveToPost.prototype.findDatasByGroup = function (options,callback) {
    //count这里用了$sum:1实现http://docs.mongodb.org/manual/reference/operator/aggregation/group/
    ActiveToPost.aggregate()
        .match(options)      //条件
        .group({_id: '$active',count: {$sum:'$reply'}})//count:指定一个字段，字段名可随意，1表示所有记录的count字段值为1,$sum在求和
        .sort('-count')                        //数组结果降序
        .project('_id')      //1表示字段返回，0：不返回
        .limit(5)                              //过滤条数
        .exec(function (err, groupDatas) {

            callback(err, groupDatas);
        });

}

ActiveToPost.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=ActiveToPost.find(q,col).sort('ActiveToPostDate').skip(obj.page.skipFrom).limit(obj.page.limit).populate('ActiveToPostUser');
    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            ActiveToPost.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null, count,pageCount, datas);
                }
            });
        }
    });

}
module.exports = ActiveToPost;
